import { myRequest } from '@/utils/request.js';

// ... (handleMyRequestSuccess 和 handleMyRequestError 辅助函数保持不变)
const handleMyRequestSuccess = (response) => {
  if (response && response.code === 1000) {
    return {
      success: true,
      data: response.data,
      message: response.msg
    };
  } else {
    return {
      success: false,
      data: response.data || null,
      message: response.msg || '服务器返回的未知错误'
    };
  }
};

const handleMyRequestError = (err) => {
  console.error('API 请求错误:', err);
  let message = '网络请求失败';
  if (err.statusCode) {
    message = `请求失败，状态码: ${err.statusCode}`;
  } else if (err.errMsg) {
    message = `请求错误: ${err.errMsg}`;
  }
  return {
    success: false,
    message: message
  };
};


const resourceService = {

  async checkOwnership(userId, resourceIds) {
    if (!userId || !resourceIds || resourceIds.length === 0) {
      return new Set(); // 如果没有资源ID或用户ID，直接返回空Set
    }
    try {
      const response = await new Promise((resolve, reject) => {
        myRequest.request({
          url: 'user-resources/check-ownership',
          method: 'POST',
          data: {
            userId: userId,
            resourceIds: resourceIds
          },
          success: resolve,
          error: reject
        });
      });
      if (response && response.code === 1000 && Array.isArray(response.data)) {
        return new Set(response.data);
      } else {
        console.error('检查所有权失败:', response.msg || '未知错误');
        return new Set(); // 出错时返回空Set
      }
    } catch (error) {
      console.error('检查所有权网络请求错误:', error);
      return new Set(); // 网络错误时返回空Set
    }
  },

  joinResource(resourceId, userId) {
    return new Promise((resolve, reject) => {
      myRequest.request({
        url: 'user-resources/join',
        method: 'POST',
        data: {
          resourceId: resourceId,
          userId: userId
        },
        success: (response) => {
          if (response && response.code === 1000) {
            resolve({ success: true, message: response.msg });
          } else {
            resolve({ success: false, message: response.msg || '加入资源失败' });
          }
        },
        error: reject
      });
    });
  },

  getJoinedResources(userId, page = 1, size = 12) {
    return new Promise((resolve, reject) => {
      const url = `user-resources/joined/${userId}?page=${page}&size=${size}`;
      myRequest.request({
        url: url,
        method: 'GET',
        success: (response) => {
          resolve(response);
        },
        error: (err) => {
          reject(err);
        }
      });
    });
  },

  getResources(params) {
    return new Promise((resolve, reject) => {
      const query = new URLSearchParams(params).toString();
      const urlWithParams = query ? `resources?${query}` : 'resources';

      myRequest.request({
        url: urlWithParams,
        method: 'GET',
        success: (response) => {
          if (response && response.code === 1000) {
            resolve({
              success: true,
              data: response.data,
              message: response.msg
            });
          } else {
            resolve({
              success: false,
              message: response.msg || '从服务器返回的未知错误'
            });
          }
        },
        error: (err) => {
          reject(err);
        }
      });
    });
  },

  createResource(formData) {
    return new Promise((resolve, reject) => {
      myRequest.formRequest({
        url: 'resources',
        method: 'POST',
        data: formData,
        success: (response) => {
          if (response && response.code === 1000) {
            resolve({ success: true, data: response.data, message: response.msg });
          } else {
            resolve({ success: false, message: response.msg || '文件上传失败' });
          }
        },
        error: reject
      });
    });
  },

  getResourceById(resourceId) {
    return new Promise((resolve, reject) => {
      myRequest.request({
        url: `resources/${resourceId}`,
        method: 'GET',
        success: (response) => {
          if(response && response.code === 1000){
            resolve({ success: true, data: response.data, message: response.msg });
          } else {
            resolve({ success: false, message: response.msg || '获取资源失败' });
          }
        },
        error: reject
      });
    });
  },

  getResourcePreviewUrl(resourceId) {
    return new Promise((resolve, reject) => {
      myRequest.request({
        url: `resources/${resourceId}/preview-url`,
        method: 'GET',
        success: (response) => {
          if (response && response.code === 1000) {
            resolve({ success: true, data: response.data });
          } else {
            resolve({ success: false, message: response.msg || '获取预览链接失败' });
          }
        },
        error: reject
      });
    });
  },

  logResourceView(userId, major) {
    return new Promise((resolve, reject) => {
      myRequest.request({
        url: 'resources/recommendations/views',
        method: 'POST',
        data: {
          userId: userId,
          major: major
        },
        success: (response) => {
          if (response && response.code === 1000) {
            resolve({ success: true, data: response.data, message: response.msg });
          } else {
            resolve({ success: false, message: response.msg || '记录浏览失败' });
          }
        },
        error: reject
      });
    });
  },

  deleteResource(resourceId) {
    return new Promise((resolve, reject) => {
      myRequest.request({
        url: `resources/${resourceId}`,
        method: 'DELETE',
        success: (response) => {
          if(response && response.code === 1000){
            resolve({ success: true, message: response.msg });
          } else {
            resolve({ success: false, message: response.msg || '删除资源失败' });
          }
        },
        error: reject
      })
    })
  },

  async getResourcesByCourseId(courseId) {
    try {
      const response = await new Promise((resolve, reject) => {
        myRequest.request({
          url: `courses/${courseId}/full-resources`,
          method: 'GET',
          success: resolve,
          error: reject
        });
      });
      return handleMyRequestSuccess(response);
    } catch (err) {
      return handleMyRequestError(err);
    }
  },

  getPersonalizedRecommendations(userId, params) {
    const query = new URLSearchParams(params).toString();
    const url = `resources/users/${userId}/recommendations?${query}`;

    return new Promise((resolve, reject) => {
      myRequest.request({
        url: url,
        method: 'GET',
        success: (response) => {
          if (response && response.code === 1000) {
            resolve({ success: true, data: response.data, message: response.msg });
          } else {
            resolve({ success: false, message: response.msg || '获取推荐失败' });
          }
        },
        error: reject
      });
    });
  },

  getResourcesByPublisherId(publisherId, query) {
    const params = new URLSearchParams();
    params.append('publisherId', publisherId);
    if (query) {
      params.append('q', query);
    }
    return new Promise((resolve, reject) => {
      myRequest.request({
        url: `resources/byPublisher/${publisherId}?${params.toString()}`,
        method: 'GET',
        success: (response) => {
          if (response && response.code === 1000) {
            resolve({ success: true, data: response.data });
          } else {
            resolve({ success: false, message: response.msg || '获取用户资源失败' });
          }
        },
        error: reject
      });
    });
  },
  getCreatedResources(userId, page = 1, size = 12) {
    return new Promise((resolve, reject) => {
      const url = `resources/by-publisher/${userId}?page=${page}&size=${size}`;
      myRequest.request({
        url: url,
        method: 'GET',
        success: (response) => {
          resolve(response);
        },
        error: (err) => {
          reject(err);
        }
      });
    });
  },
};

export default resourceService;